package com.sxit.myproscenium.system.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;
import com.sxit.myproscenium.common.exception.ServerException;
import com.sxit.myproscenium.common.response.R;
import com.sxit.myproscenium.system.controller.form.LoginForm;
import com.sxit.myproscenium.system.controller.form.RegisterForm;
import com.sxit.myproscenium.system.entity.User;
import com.sxit.myproscenium.system.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;

/**
 * @author 胡乖乖童鞋
 * @date 2022/4/13 9:22
 * @describe
 */
@RestController
@RequestMapping("/system/login")
public class UserLoginController {

  @Autowired IUserService userService;

  @GetMapping("/isLogin")
  public R isLogin() {
    HashMap<String, Boolean> stringHashMap = new HashMap<String, Boolean>();
    stringHashMap.put("isLogin", StpUtil.isLogin());
    return R.ok().put("data", stringHashMap);
  }

  @PostMapping("/login")
  public R login(@RequestBody @Validated LoginForm loginForm) {

    User user = userService.findByUsername(loginForm.getUsername());

    if (user == null) {
      throw new ServerException("用户名不存在");
    }

    if (!user.getWxPassword().equals(loginForm.getPassword())) {
      throw new ServerException("用户名或密码错误");
    }

    StpUtil.login(user.getUserId());
    SaTokenInfo tokenInfo = StpUtil.getTokenInfo();

    user.setPassword("");
    user.setWxPassword("");
    return R.ok().put("data", tokenInfo.getTokenValue());
  }

  @GetMapping("/getUserInfo")
  @SaCheckLogin
  public R getUserInfo() {
    long loginIdAsLong = StpUtil.getLoginIdAsLong();
    User byId = userService.getById(loginIdAsLong);
    byId.setPassword("");
    byId.setWxPassword("");
    return R.ok().put("data", byId);
  }

  @PostMapping("/register")
  public R register(@RequestBody @Validated RegisterForm registerForm) {

    User byUsername = userService.findByUsername(registerForm.getUsername());
    if (byUsername != null) {
      throw new ServerException("用户名已经存在");
    }

    User user = new User();
    user.setUserName(registerForm.getUsername());
    user.setNickName(registerForm.getNickName());
    user.setUserType("01");

    user.setCreateTime(LocalDateTime.now());
    user.setWxPassword(registerForm.getPassword());
    user.setStatus("0");

    boolean save = userService.save(user);

    if (save) {
      return R.ok("创建成功");
    } else {
      return R.error("创建失败");
    }
  }

  @GetMapping("/loginOut")
  public R loginOut() {
    StpUtil.logout();
    return R.ok();
  }
}
